<template>
	<el-container class="user-page" v-if="!showOrgChart">
		<el-aside width="260px">
		<el-container>
			<el-header>
				<el-input placeholder="输入关键字进行过滤" v-model="deptFilterText" clearable></el-input>
			</el-header>
			<el-main class="nopadding" v-loading="loading.dept">
				<el-tree ref="depts" class="menu" node-key="id" default-expand-all :data="depts" :draggable="modifyDept" highlight-current accordion :highlight-current="true" :expand-on-click-node="false" :filter-node-method="deptFilterNode" :current-node-key="currentNodekey" @node-click="deptClick" @node-contextmenu="contextMenu" style="padding: 10px">
					<template #default="{node, data}">
						<span class="custom-tree-node" :class="modifyDept?'modify':''">
							<span class="label">{{ data.label }}</span>
							<span class="do" v-if="modifyDept">
								<el-button-group>
									<el-button icon="el-icon-edit" size="small" @click.stop="deptModify(node, data)"></el-button>
									<el-button icon="el-icon-delete" size="small" @click.stop="deptDelete(node, data)"></el-button>
								</el-button-group>
							</span>
						</span>
					</template>
          		</el-tree>
				<jd-contextmenu ref="contextmenu" @command="handleCommand">
					<jd-contextmenu-item command="modify" title="编辑部门" suffix="Alt+←" icon="el-icon-edit"></jd-contextmenu-item>
					<jd-contextmenu-item command="manager" title="设置主管" suffix="Ctrl+R" icon="el-icon-scheck"></jd-contextmenu-item>
					<jd-contextmenu-item command="member" title="添加成员" divided icon="el-icon-avatar"></jd-contextmenu-item>
					<jd-contextmenu-item  command="enable" title="启用部门" divided></jd-contextmenu-item>
					<jd-contextmenu-item  command="disable" title="禁用部门"></jd-contextmenu-item>
					<jd-contextmenu-item  command="delete" title="删除部门" divided  icon="el-icon-delete"></jd-contextmenu-item>
				</jd-contextmenu>
			</el-main>
			<el-footer style="height: 51px">
			<el-button-group style="width: 100%">
				<el-button :type="modifyDept ? 'danger' : 'primary'" size="small" icon="el-icon-money" @click="openEdit" style="width: 50%">
					<span v-if="!modifyDept">开启编辑</span>
					<span v-else>结束编辑</span>
				</el-button>
				<el-button type="success" size="small" icon="el-icon-set-up" @click.stop="addDept(0,0)" style="width: 50%">新增部门</el-button>
			</el-button-group>
			</el-footer>
		</el-container>
		</el-aside>
		<el-container>
			<el-header>
				<div class="left-panel">
					<el-button type="primary" icon="el-icon-plus" @click="addDept(0, nodeId)"></el-button>
					<!-- <el-button type="danger" plain icon="el-icon-delete" v-if="showCheckBox" :disabled="selection.length == 0" @click="batchDelete" v-auth="'system:user:remove'"></el-button> -->
				</div>
				<div class="right-panel">
					<div class="right-panel-search">
						<el-input ref="searchInput" v-model="search.keyword" minlength="1" maxlength="20" placeholder="账号/姓名/手机号" clearable></el-input>
						<el-button type="primary" icon="el-icon-search" @click="memberSearch"></el-button>
						<el-button type="text" icon="el-icon-menu" @click="changeOrgChart">组织架构</el-button>
					</div>
				</div>
			</el-header>
			<el-main>
				<el-scrollbar class="deptScroll" v-loading="loading.childDept">
					<el-row>
						<el-col :span="8" v-for="(item,index) in childDepts" :key="index" class="dept-col">
							<el-card shadow="hover" class="dept-card" :class="item.id==childDeptId?'current':''" @click="childDeptClick(item)">
								<el-row type="flex" align="middle" class="dept-rows">
									<el-col :span="24" class="body__wrap">
										<el-avatar class="avatar__wrap">
											<div class="defalut-img">{{ item.label.slice(0, 1) }}</div>
										</el-avatar>
										<div>
											<div class="name">{{ item.label }}</div>
											<div class="phone">
												<span v-if="item.leader==null">
													暂无主管
												</span>
												<span v-else>
													主管：{{ item.leader }} 
												</span>
												<span style="margin-left: 15px;">
													共 {{ item.nums }} 人
												</span>
											</div>
										</div>
									</el-col>
									<el-popconfirm title="确定要删除吗？" @confirm="delDeveloper(developer, $event)" v-if="showCheckBox">
										<template #reference>
											<el-icon class="close-icon" style="font-size: 20px"><el-icon-delete /></el-icon>
										</template>
									</el-popconfirm>
								</el-row>
								<div style="position: absolute; right: 10px; top: 10px" v-if="item.id==childDeptId">
									<el-icon-select style="width: 24px; color: #409eff;"/>
								</div>
							</el-card>
						</el-col>
						<el-col :span="8" v-if="childDepts.length==0">
							<el-card shadow="hover" class="dept-card">
								<el-row type="flex" align="middle" class="dept-rows">
									<el-col :span="24" style="text-align: center">
										<el-button text icon="el-icon-plus" @click="addDept(0, nodeId)" style="margin: 0px; padding: 0px; font-size: 16px; ">添加子部门</el-button>
									</el-col>
								</el-row>
							</el-card>
						</el-col>
					</el-row>
				</el-scrollbar>
				<el-card class="box-card" shadow="never">
					<template #header>
						<el-row type="flex" align="middle">
							<el-col :span="16">成员列表</el-col>
							<el-col :span="8" style="text-align: right;">
								<el-button text type="primary" icon="el-icon-plus" class="button" @click="memberAdd">添加会员</el-button>
							</el-col>
						</el-row>
					</template>
					<jdTable ref="table" height="calc(100vh - 385px)" :apiObj="apiObj" size="large" @selection-change="selectionChange" :params="params" stripe hideDo hideSetting hideRefresh v-loading="loading.member">
						<el-table-column label="账号" prop="userName" min-width="150" fixed="left"></el-table-column>
						<el-table-column label="姓名" prop="nickName" min-width="150" fixed="left"></el-table-column>
						<el-table-column label="手机号" prop="phone" min-width="150"></el-table-column>
						<el-table-column label="角色" prop="roleName" min-width="150"></el-table-column>
						<el-table-column label="状态" prop="status" width="150" align="center">
							<template #default="scope">
								<DictTag :options="dict.status" :value="scope.row.status"></DictTag>
							</template>
						</el-table-column>
						<el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>
						<el-table-column label="操作" fixed="right" align="center" width="150">
							<template #default="scope">
								<el-button-group>
									<el-button text type="primary" @click="memberModify(scope.row, scope.$index)" class="button">编辑</el-button>
									<el-popconfirm title="确定要删除吗？" @confirm="memberDelete(scope.row, scope.$index)">
										<template #reference>
											<el-button text type="primary" class="button">删除</el-button>
										</template>
									</el-popconfirm>
								</el-button-group>
							</template>
						</el-table-column>
					</jdTable>
				</el-card>
			</el-main>
		</el-container>
	</el-container>
	<el-container class="user-page" v-else>
    <el-main style="background: #FFF;">
      <div class="orgChart">
        <el-button type="text" icon="el-icon-close" @click="changeOrgChart" class="close">关闭架构</el-button>
        <vue3-tree-org
          :data="depts[0]"
          center
          :horizontal="horizontal"
          :collapsable="collapsable"
          :label-style="style"
          :scalable="scalable"
          :only-one-node="onlyOneNode"
          :clone-node-drag="cloneNodeDrag"
          :before-drag-end="beforeDragEnd"
          :toolBar="toolBar"
          @on-node-click="onDeptClick"
        />
      </div>
    </el-main>
  </el-container>
  
  <select-dialog v-if="dialog.select" ref="selectDialog" :multiple="false" @success="handleSaveSuccess" @closed="dialog.select = false"></select-dialog>
  <save-dialog v-if="dialog.save" ref="saveDialog" :deptId="nodeId" @success="handleSaveSuccess" @closed="dialog.save=false"></save-dialog>

</template>

<script>
	import saveDialog from '../member/save'
	import selectDialog from "../member/select.vue"
	import jdContextmenu from '@/components/jdContextmenu'
	import jdContextmenuItem from '@/components/jdContextmenu/item'
	import PinYin from 'js-pinyin';

	export default {
		name: 'dept',
		components: {
			saveDialog,
			selectDialog,
			jdContextmenu,
			jdContextmenuItem
		},
		data() {
			return {
				dialog: {
					save: false,
					select: false,
				},
				dict:{
					sex:[],
					status:[],
				},
				loading:{
					dept: false,
					childDept: false,
					member: false
				},
				apiObj: this.$API.system.member.list,
				params: {},
				selection: [],
				search: {
					keyword: null
				},
				modifyDept: false,
				currentNodekey: "",
				node: [],
				nodeId: 0,
				deptFilterText: '',
				depts: [],
				childDepts: [],
				childDeptId: 0,
				showCheckBox: false,
				showOrgChart: false,
				horizontal: false,
				collapsable: false,
				onlyOneNode: false,
				expandAll: true,
				scalable: true,
				toolBar: {
					scale: false, restore: true, expand: true, zoom: true, fullscreen: true, 
				},
				style: {
					background: "#409EFF",
					color: "#FFFFFF",
					cursor: "pointer"
				},
			}
		},
		watch: {
			deptFilterText(val) {
				this.$refs.depts.filter(val);
			}
		},
		mounted() {
			// 加载配置字典
			this.getDict();
			// 加载部门列表
			this.getDepts();
		},
		methods: {
			// 字典获取
			async getDict() {
				this.dict = {
					status: await this.Dict.get("sys_normal_disable")
				}
			},
			// 加载部门列表
			async getDepts() {
				this.loading.dept = true;
				var res = await this.$API.system.dept.tree.get()
				if (res.code == 200) {
					this.depts = res.data

					if (this.depts.length > 0) {
						this.currentNodekey = this.depts[0].id;
						this.$nextTick(() => {
							this.$refs.depts.setCurrentKey(this.currentNodekey);
							this.getChildDepts(this.currentNodekey);
						});
					}

					this.loading.dept = false;
				}
			},
			// 加载子部门列表
			async getChildDepts(parentId) {
				this.loading.childDept = true;
				var res = await this.$API.system.dept.childList.get(parentId)
				if (res.code == 200) {
					this.childDepts = res.data;
					this.loading.childDept = false;
				}
			},
			// 加载部门会员列表
			async getChildMembers(deptId) {
				var params = {
					dept: deptId
				}
      			this.$refs.table.reload(params);
			},
			// 打开右键菜单
			contextMenu(event, data, node, self){
				if (!this.modifyDept){
					return;
				}
				this.nodeId = data.id;
				this.node = node;
				// 打开右键菜单
				this.$refs.contextmenu.openMenu(event)
			},
			handleCommand(command){
				if(command == 'modify'){
					this.deptModify(this.node, this.node.data);
				}
				if(command == 'manager'){
					this.leaderSelect(this.node, this.node.data);
				}
				if(command == 'member'){
					this.memberAdd();
				}
				if(command == 'enable'){
					this.deptStatus(this.node, this.node.data, 0);
				}
				if(command == 'disable'){
					this.deptStatus(this.node, this.node.data, 1);
				}
				if(command == 'delete'){
					this.deptDelete(this.node, this.node.data);
				}
			},
			// 设置主管
			leaderSelect(){
				this.dialog.select = true;
				this.$nextTick(() => {
					this.$refs.selectDialog.open(this.nodeId, 'dept');
				})
			},
			// 开启编辑
			openEdit(){
				this.modifyDept=!this.modifyDept;
				if (this.modifyDept){
					this.$message.success("编辑模式，部门树可使用右键菜单")
				}
			},
			// 显示部门架构
			changeOrgChart(){
				this.showOrgChart=!this.showOrgChart;
			},
			//树点击
			deptClick(data,node){
				this.node = node;
				this.nodeId = data.id;

				// 加载子部门列表
				this.getChildDepts(data.id);
				// 加载部门会员列表
				this.getChildMembers(data.id);
			},
			// 子部门点击
			childDeptClick(row){
				if (!this.showCheckBox){
					this.nodeId = row.id;
					this.childDeptId = row.id;
					this.getChildMembers(row.id);
				}
			},
			// 树过滤
			deptFilterNode(value, data){
				if (!value) return true;
				var targetText = data.label;
				return targetText.indexOf(value) !== -1;
			},
			// 新增部门
			addDept(menuId,pid){
				if (pid == 0){
					// 清空节点
					this.nodeId = 0;
				}
				var parentId = this.nodeId
				this.$prompt('部门名称', '新建部门', {
					inputPlaceholder: '请输入一个部门名称',
					inputPattern: /\S/,
					inputErrorMessage: '部门名称不能为空'
				})
				.then(async ({ value }) => {
					var data = {
						label: value,
						parentId: parentId
					}
					var res = await this.$API.system.dept.addDept.post(data);
					if(res.code == 200){
						var nodeData = {
							id: res.data,
							label: data.label
						}
						this.refreshNode(nodeData, 'append');
						this.getChildDepts(parentId);
						this.$message.success("操作成功")
					}else{
						this.$alert(res.msg, "提示", {type: 'error'})
					}
				});
			},
			// 编辑部门
			async deptModify(node, data){
				console.log(data);
				var deptId = data.id;
				this.$prompt('部门名称', '编辑部门', {
					inputPlaceholder: '请输入一个部门名称',
					inputPattern: /\S/,
					inputErrorMessage: '部门名称不能为空',
					inputValue: data.label
				})
				.then(async ({ value }) => {
					// 获取拼音首字母
					PinYin.setOptions({ checkPolyphone: false, charCase: 0 })
					var postCode = PinYin.getCamelChars(value)

					var data = {
						id: deptId,
						label: value
					}
					var res = await this.$API.system.dept.deptModify.put(data);
					if(res.code == 200){
						let updateNode = this.$refs.depts.getNode(node);
						console.log(updateNode)
						if (updateNode) {
							updateNode.data.label = value
							//updateNode.data.id = postCode
						}
						this.$message.success("操作成功")
					}else{
						this.$alert(res.msg, "提示", {type: 'error'})
					}
				});
			},
			// 设置状态
			async deptStatus(node, data, status){
				var data = {
					id: data.id,
					status: status
				}
				var res = await this.$API.system.dept.changeStatus.put(data);
				if (res.code == 200){
					this.$message.success("操作成功")
				}else{
					this.$alert(res.msg, "提示", {type: 'error'})
				}
			},
			// 删除部门
			async deptDelete(node, data){
				var res = await this.$API.system.dept.deleteDept.delete(data.id);
				if (res.code == 200){
					let deleteNode = this.$refs.depts.getNode(node);
					this.$refs.depts.remove(deleteNode);
					this.$message.success("操作成功")
				}else{
					this.$alert(res.msg, "提示", {type: 'error'})
				}
			},
			// 更新节点
			refreshNode(data,mode){
				if (mode == "append"){
					var nodeData = {
						id: data.id,
						label: data.label
					}
					if (this.nodeId == 0){
						this.$refs.depts.append(nodeData);
					}
					else {
						console.log('this.nodeId',this.nodeId)
						let parentNode = this.$refs.depts.getNode(this.node);
						console.log('parentNode',parentNode)
						this.$refs.depts.append(nodeData,parentNode);
					}
				} else {
					let updateNode = this.$refs.depts.getNode(this.node);
					if (updateNode) {
						updateNode.loaded = false;
						updateNode.data.label = data.menuName;
						updateNode.expand();
					}
				}
			},
			refreshCache(){
				this.$confirm('此操作将重置岗位的缓存, 是否要继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					await this.$API.system.dict.type.refreshCache.delete();
					this.$message.success("操作成功");
				}).catch(() => {
				});
			},
			// 会员搜索
			memberSearch() {
				this.params.searchValue = this.search.keyword;
			},
			// 增加会员
			memberAdd(){
				this.dialog.save = true
				this.$nextTick(() => {
					this.$refs.saveDialog.open()
				})
			},
			// 会员编辑
			async memberModify(row) {
				let res = await this.$API.system.member.getUser.get(row.memberId)
				if (res.code == 200) {
					if (res.roleIds != null) {
					res.data.roleIds = res.roleIds[0]
					}
					this.dialog.save = true
					await this.$nextTick(() => {
						this.$refs.saveDialog.open("edit").setData(res.data)
					})
				}
			},
			// 会员删除
			async memberDelete(row) {
				var res = await this.$API.system.member.delUser.delete(row.memberId)
				if (res.code == 200) {
					this.$refs.table.refresh()
					this.$message.success("删除成功")
				} else {
					this.$alert(res.msg, "提示", { type: "error" })
				}
			},
			//表格选择后回调事件
			selectionChange(selection){
				this.selection = selection;
			},
			//本地更新数据
			handleSaveSuccess(){
				this.$refs.table.refresh()
			}
		}
	}
</script>

<style lang="scss" scoped>
.menu:deep(.el-tree-node__label) {display: flex;flex: 1;height:100%;}
.custom-tree-node {display: flex;flex: 1;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 24px;height:100%;}
.custom-tree-node .label{width: 90px;text-overflow: ellipsis; overflow: hidden;}
.custom-tree-node .code {font-size: 12px;color: #999;}
.custom-tree-node .do {display: none;}
.custom-tree-node:hover {color: #409eff;}
.custom-tree-node:hover .code {display: none;}
.custom-tree-node:hover .do {display: inline-block;animation: fadeIn;animation-duration: 1s;}
.custom-tree-node.disabled{text-decoration:line-through; color: #aaa;}
.custom-tree-node.disabled .code {font-size: 12px;color: #aaa;}
.custom-tree-node.modify{color: #58a034;}
.orgChart{ width: 100%;height: calc(100% - 30px); font-size: 16px;text-align: right;}

.dept-col{padding-right: 15px;}
.dept-col:nth-child(3n) {padding-right: 0px;}
.deptScroll{height: 120px;overflow: hidden !important;}
.dept-card {
	position: relative;
	cursor: pointer;
	.el-card__body {
		padding: 10px;
	}
	.dept-rows {
		justify-content: space-between;
		align-items: center;
		position: relative;
		box-sizing: border-box;
		cursor: pointer;
		height: 65px;
		.avatar__wrap {
		margin-right: 10px;
		width: 60px;
		height: 60px;
		flex-shrink: 0;
		.defalut-img {
			width: 100%;
			height: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #409eff;
			font-size: 28px;
			font-weight: bold;
			font-family: Verdana, Geneva, Tahoma, sans-serif;
		}
	}
    .body__wrap {
      display: flex;
      align-items: center;
      color: var(--el-text-color-regular);
      .name {
        font-size: 16px;
        font-weight: bolder;
        margin-bottom: 5px;
      }
      .phone {
        width: 100%;
        font-size: 14px;
      }
    }
    .close-icon {
      position: absolute;
      top: -10px;
      right: -10px;
      color: #7e7b7b;
	  display: none;
    }
  }
  &:hover {
    .close-icon {
		display: block;
		animation: fadeIn;
		animation-duration: 1s;
    }
  }
}
.dept-card.current{
	background: #ebf5ff;
}
</style>
